﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LinnCorLib.Net;


namespace MonsterMessenger.Forms
{
    public partial class BetaTestForm : Form
    {
        ChatClient client = null;


        public BetaTestForm()
        {
            InitializeComponent();

            client = new ChatClient();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            SendMessage();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtID.Text) == true)
            {
                MessageBox.Show("아이디는 필수!");
                return;
            }
            
            if (client.Connected == true)
            {
                MessageBox.Show("이미 접속중");
                return;
            }

            client.ConnectServer(txtServerIP.Text, 7777);
            client.ReceiveMessageEvent += new EventHandler<ReceiveMessageEventArgs>(client_ReceiveMessageEvent);
        }

        void client_ReceiveMessageEvent(object sender, ReceiveMessageEventArgs e)
        {
            txtChat.Invoke(new Action(delegate()
                {
                    txtChat.Select(txtChat.TextLength, 0);
                    txtChat.AppendText(e.message + "\n");
                    txtChat.ScrollToCaret();
                }));
        }


        private void SendMessage()
        {
            if (client.Connected == false)
            {
                MessageBox.Show("Monster Server에 접속되지 않았습니다.");
                return;
            }

            client.SendMessage(GetMessageFormat(txtID.Text, txtMessage.Text));

            txtMessage.Text = "";
        }

        private string GetMessageFormat(string id, string msg)
        {
            return string.Format("[{0}]{1}", id, msg);
        }

        private void txtMessage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                SendMessage();
        }

        private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = e.KeyChar == (char)Keys.Enter;
        }

        private void BetaTestForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (client != null)
            {
                client.Disconnect();
                client = null;
            }
        }
    }
}
